package org.go.scheduler.database.concurrent;

import java.sql.Connection;

import org.go.expcetion.LockException;

/**
 * An interface for providing thread/resource locking in order to protect
 * resources from being altered by multiple threads at the same time.
 * 
 * @author jhouse
 */
public interface Semaphore {

	/**
	 * Determine whether the calling thread owns a lock on the identified
	 * resource.

	 * @param conn Database connection used to establish lock.  Can be null if
	 * <code>{@link #requiresConnection()}</code> returns false.
	 */
	boolean isLockOwner(Connection conn, String lockName) throws LockException;

	/**
	 * Grants a lock on the identified resource to the calling thread (blocking
	 * until it is available).
	 * 
	 * @param conn Database connection used to establish lock.  Can be null if
	 * <code>{@link #requiresConnection()}</code> returns false.
	 * 
	 * @return true if the lock was obtained.
	 */
	boolean obtainLock(Connection conn, String lockName) throws LockException;

	/**
	 * Release the lock on the identified resource if it is held by the calling
	 * thread.

	 * @param conn Database connection used to establish lock.  Can be null if
	 * <code>{@link #requiresConnection()}</code> returns false.
	 */
	void releaseLock(Connection conn, String lockName) throws LockException;

	/**
	 * Whether this Semaphore implementation requires a database connection for
	 * its lock management operations.
	 * 
	 * @see #isLockOwner(Connection, String)
	 * @see #obtainLock(Connection, String)
	 * @see #releaseLock(Connection, String)
	 */
	boolean requiresConnection();
}
